require "digest/sha1"

class Merchant < ActiveRecord::Base
  
  attr_accessor :password_confirmation
  
  has_one :store
  
  validates_uniqueness_of :username, :message => "注册的用户名已经存在"
  validates_presence_of :username, :message => "必须填写用户名"
  validates_confirmation_of :password, :message => "密码和确认密码必须相同"
  validates_presence_of :hashed_password, :message => "必须填写密码"
  
  def before_create
    self.last_login_time = Time.now
  end
  
  def validate
    errors.add_to_base("没有填写密码") if hashed_password.blank?
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    self.hashed_password = Merchant.hash_password(@password)
  end
  
  def name
    self.username
  end
  
  def self.login(username, password)
    hashed_password = hash_password(password || "")
    find(:first, :conditions => ["username = ? AND hashed_password = ?", username, hashed_password])
  end
  
  private
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
